<?php

/**
 * 用户model类
 * Class user
 */
    class user{
        private $db;
        function __construct(){
            $this->db=$GLOBALS['db'];
        }

        function binding_phone($phone_num){
            if($uid=session("uid")){
                if($this->db->get_one("select UI.*,AI.4s_id from user_info as UI
                                              left join admin_info as AI on UI.admin_id=AI.admin_id
                                              where UI.phone_num='$phone_num' and UI.open_id!=''")){
                                              throw new Exception("该手机号已被绑定过，请换个手机号试试",USER_INPUT_ERROR);
                }
                if($is_back_register=$this->db->get_one("select UI.*,AI.4s_id from user_info as UI
                                              left join admin_info as AI on UI.admin_id=AI.admin_id
                                              where UI.phone_num='$phone_num' and UI.open_id=''")){
                    $now_user_info=$this->db->get_one("select * from user_info where user_id=$uid");
                    $sql=array();
                    $user_info=$this->get_info_by_id();
                    if( $is_back_register['name']){
                        session("user_name", $is_back_register['name']);
                        $sql[]="name='".$is_back_register['name']."'";
                    }
                    if(($now_user_info['birthday']=="0000-00-00") && $is_back_register['birthday']){
                        $sql[]="birthday='".$is_back_register['birthday']."'";
                    }
                    if( $is_back_register['address']){
                        $sql[]="address='".$is_back_register['address']."'";
                    }
                    if( $is_back_register['sex']){
                        $sql[]="sex=".$is_back_register['sex'];
                    }
                    if( $is_back_register['driving_license']){
                        $sql[]="driving_license='".$is_back_register['driving_license']."'";
                    }
                    if( $is_back_register['admin_id']){
                        $sql[]="admin_id=".$is_back_register['admin_id'];
                    }
                    if( $is_back_register['city_id']){
                        $sql[]="city_id=".$is_back_register['city_id'];
                    }
                    if( $is_back_register['create_time']){
                        $sql[]="create_time='".$is_back_register['create_time']."'";
                    }
                    if( $is_back_register['credit']){
                        $sql[]="credit=`credit`+".$is_back_register['credit'];
                    }
                    if( $is_back_register['rmb']){
                        $sql[]="`rmb`=`rmb`+".$is_back_register['rmb'];
                    }
                    if(!empty($sql)){
                        $sql=implode(",", $sql);
                        $this->db->query("update user_info set $sql where user_id=$uid");
                    }
                    include_once BASE_PATH."/model/credit.model.php";
                    $credit=new credit();
                    $credit->log(100004, $uid, 1, $is_back_register['credit'], $user_info['credit'],"合并账号".$is_back_register['user_id']);
                    
                    $this->db->query("update order_info set user_id=$uid where user_id=".$is_back_register['user_id']);
                    $this->db->query("update user_car_mapping set user_id=$uid where user_id=".$is_back_register['user_id']);
                    $this->db->query("delete from user_info where open_id='' and user_id=".$is_back_register['user_id']);
                    $this->db->query("delete from user_4s_mapping where  user_id=".$is_back_register['user_id']);
                    if(isset($is_back_register['4s_id']) && !empty($is_back_register['4s_id']) && isset($is_back_register['admin_id']) && !empty($is_back_register['admin_id'])){
                        include_once BASE_PATH."/model/fs.model.php";
                        $fs=new fs();
                        $fs->set_user_4s_admin_id($uid, $is_back_register['4s_id'], $is_back_register['admin_id']);
                    }
                }
                $this->update_binding_phone($uid, $phone_num);
                session("phone_num", $phone_num);
                return true;
            }
        }

        function getUserInfo_by_session(){

            $union_id   = session("union_id");
            $open_id    = session("open_id");
            $account    = $GLOBALS['account'];

            if($union_id){
                $wxU=$this->db->get_one("select * from u_user_weixin where WX_unionID='{$union_id}'");
            }else{
                $wxU=$this->db->get_one("select * from u_user_weixin where WX{$account}_openID='{$open_id}'");
            }

            if(!$wxU){
                return null;
            }else{
                $baseUinfo= $this->db->get_one("select * from u_user_base where uid={$wxU['uid']}");
                return array_merge($baseUinfo,$wxU);
            }
        }



        
        function login(){
            $open_id    = session("open_id");
            $account    = $GLOBALS['account'];
            $now        = time();

            if($user_info=$this->getUserInfo_by_session()){
                if(!$user_info['nickname']){
                    $this->db->query("update u_user_base set nickname='".addslashes(session('nickname'))."' where uid=".$user_info['uid']);
                }
                $uid=$user_info['uid'];
                //session_multi(array("user_name"=>$user_info['name'],"uid"=>$user_info['user_id'],"phone_num"=>$user_info['phone_num']));
                if(strlen($user_info["WX{$account}_openID"])<5){
                    $this->db->query("update `u_user_weixin`
                      set `WX{$account}_openID`='{$open_id}',
                          `WX{$account}_subscribeTime`={$now}
                      where `uid`={$uid}");
                }
            }
            else{
                //log::write("login.openid", time().$open_id.PHP_EOL);

                $nickName=addslashes(session("nickname"));
                $this->db->query("insert into `u_user_base`
                      set `nickname`='{$nickName}',
                          `regTime`={$now},
                          `regFrom`=".CLIENT_FROM_WX);
                $uid=$this->db->insert_id();

                $unionid=session("union_id");
                $this->db->query("insert into `u_user_weixin`
                      set `uid`={$uid},
                          `WX_unionID`='{$unionid}',
                          `WX{$account}_openID`='{$open_id}',
                          `WX{$account}_subscribeTime`={$now}");


                //session_multi(array("user_name"=>"","uid"=>$uid,"phone_num"=>""));
            }
            session('uid',$uid);
            //$this->update_user_last_login_time($uid);

            $d=date('Y-m-d');
            $dir=session('uid') % \Common\Model\UserModel::USER_HEADPIC_DEVIDE;
            $filename=BASE_PATH."/upload/user/head/{$dir}/".session("uid").".jpg";
            if(!is_file($filename)){
                file_put_contents($filename, file_get_contents(session("pic")));
                $show_pic_scal=show_pic_scal(50, 50, $filename);
                resize($filename,$show_pic_scal[0],$show_pic_scal[1]);
            }
            if(!session($d)){
                session($d,1);
                //$this->db->query("replace into user_login values('$d',".session("uid").")");
            }
        }
        
        
        function update_binding_phone($uid,$phone){
            $binding_time=$this->db->get_one("select binding_time from `user_info` where `user_id`=$uid","binding_time");
            $this->db->query("insert into binding_info(uid,phone,`time`,`info_id`) values($uid,'$phone',NOW(),null)");
            if(strtotime($binding_time)>10000){
                 return $this->db->query("UPDATE `user_info`
                SET
                `phone_num` = '$phone'
                WHERE `user_id` = $uid;");
            }
            else{
                return $this->db->query("UPDATE `user_info`
                    SET
                    `phone_num` = '$phone',
                    binding_time=NOW()
                    WHERE `user_id` = $uid;");
            }
        }
        
        function change_info($uid,$name,$birthday,$address,$sex,$driving_license,$city_id,$phone_num,$nickname){
            return $this->db->query("UPDATE `jiaochenhui`.`user_info` 
                              SET 
                             `name` = '$name', 
                             `birthday` = '$birthday',
                             `sex` = '$sex',
                             `contact_phone`='$phone_num',
                             `nickname`='$nickname'
                              WHERE `user_info`.`user_id` = $uid;");
        }
        
        
        function get_open_id(){
            include_once BASE_PATH."/soeLib/weixin/weixin.class.php";
            $weixin=new weixin();
            if($value=$weixin->get_open_id()){
                session("open_id", $value[0]);
                session("access_token", $value[1]);
                session("refresh_token", $value[2]);
                $userinfo=$weixin->get_userinfo($value[0],$value[1],$value[2]);
                session("pic", $userinfo['headimgurl']);
                session("nickname", $userinfo['nickname']);
            }
            else{
                throw new Exception("微信接口数据获取失败！",1005);
            }
        }
        
        function login_by_weixin(){

            if(!session("open_id")){
                if(!filter::get_user_input("code") && !filter::get_user_input("open_id")){
                    header("Location:".wxJumper::get_url_weixin_auth2($_SERVER['QUERY_STRING']));
                    exit;
                }
                else{
                    include_once BASE_PATH."/soeLib/weixin/weixin.class.php";
                    $weixin=new \weixin();
                    if($value=$weixin->get_open_id()){
                        session("open_id", $value[0]);
                        session("access_token", $value[1]);
                        session("refresh_token", $value[2]);
                        session("union_id", $value[3]);
                        $userinfo=$weixin->get_userinfo($value[0],$value[1],$value[2],$value[3]);
                        @session("pic", $userinfo['headimgurl']);
                        @session("nickname", $userinfo['nickname']);
                    }
                    else{
                        throw new Exception("微信接口数据获取失败！",1005);
                    }
                }
            }
            if(!session("pic") || !session("nickname")){
                include_once BASE_PATH."/soeLib/weixin/weixin.class.php";
                $weixin=new weixin();
                $userinfo=$weixin->get_userinfo(session("open_id"),session("access_token"),session("refresh_token"));
                @session("pic", $userinfo['headimgurl']);
                @session("nickname", $userinfo['nickname']);
            }
        }

        function create_sms_verify($phone_num,$code){
            return $this->db->query("insert into `sms_verify_code` values(null,'$phone_num','$code',NOW(),1)");
        }
        function verify_code($phone_num,$verify_code){
            return $this->db->get_one("select * from `sms_verify_code` where `phone_num`='$phone_num' and verify_code='$verify_code' and TIMESTAMPDIFF(SECOND, create_time, NOW())<".(1800)."");
        }
        
        function set_sms_verify_status($phone_num,$code){
            return $this->db->query("update `sms_verify_code` set `status`=2 where phone_num='$phone_num' and verify_code='$code'");
        }
        
        function get_order_by_user($uid){
            return $this->db->get_array("select CB.brand_id, CB.name as brand_name, FI.longitude,FI.latitude,FI.short_name,FI.address as 4s_address, CII.comment_id,AI.name as admin_name,AI.account as admin_phone, OI.*,CI.car_license,CT.name 
                from order_info as OI 
                left join 4s_info as FI on OI.4s_id=FI.4s_id
                left join car_info as CI on OI.car_id=CI.car_id 
                left join car_type as CT on CI.car_type_id=CT.type_id
                left join car_brand as CB on CB.brand_id=CT.brand_id 
                left join admin_info as AI on OI.service_id=AI.admin_id
                left join comment_info as CII on OI.order_id=CII.order_id
                where OI.user_id=$uid and (OI.order_type=1 or OI.order_type=2 or OI.order_type=3) order by order_id desc");
        }
        
        function delete(){
            if($uid=session("uid")){
                return $this->db->query("delete from user_info where user_id=$uid");
            }
        }
        
        function get_admin_id(){
            if($phone_num=session("phone_num")){
                if($admin_info=$this->db->get_one("select * from admin_info where account=$phone_num")){
                    session("admin_id", $admin_info['admin_id']);
                }
            }
        }
        
        function get_admin_openid($phone_num){
            return $this->db->get_one("select open_id from user_info where phone_num='$phone_num'","open_id");
        }
    }